<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>好友请求</span>
          <el-button type="primary" @click="goBack">返回好友列表</el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="收到的请求" name="received">
          <el-empty v-if="receivedRequests.length === 0" description="暂无收到的好友请求" />
          <div v-else class="request-list">
            <el-card
              v-for="request in receivedRequests"
              :key="request.id"
              class="request-card"
              shadow="hover"
            >
              <div class="request-info">
                <el-avatar :size="50" :src="request.senderAvatar">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                </el-avatar>
                <div class="request-details">
                  <div class="request-name">{{ request.senderName }}</div>
                  <div class="request-time">{{ formatTime(request.createdAt) }}</div>
                  <div class="request-message">
                    <el-tooltip :content="request.message" placement="top" :hide-after="2000">
                      <span>{{ truncateMessage(request.message) }}</span>
                    </el-tooltip>
                  </div>
                </div>
              </div>
              <div class="request-actions">
                <el-button type="primary" @click="acceptRequest(request)">接受</el-button>
                <el-button type="danger" @click="rejectRequest(request)">拒绝</el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>

        <el-tab-pane label="发出的请求" name="sent">
          <el-empty v-if="sentRequests.length === 0" description="暂无发出的好友请求" />
          <div v-else class="request-list">
            <el-card
              v-for="request in sentRequests"
              :key="request.id"
              class="request-card"
              shadow="hover"
            >
              <div class="request-info">
                <el-avatar :size="50" :src="request.receiverAvatar">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                </el-avatar>
                <div class="request-details">
                  <div class="request-name">{{ request.receiverName }}</div>
                  <div class="request-time">{{ formatTime(request.createdAt) }}</div>
                  <div class="request-status">
                    <el-tag :type="getStatusType(request.status)" size="small">
                      {{ getStatusText(request.status) }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <div class="request-actions">
                <el-button
                  v-if="request.status === 'pending'"
                  type="danger"
                  @click="cancelRequest(request)"
                >
                  取消请求
                </el-button>
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getFriendRequests, acceptFriendRequest, rejectFriendRequest } from "@/api/social";
import type { FriendRequestInfo } from "@/types/social";

const router = useRouter();
const activeTab = ref("received");
const receivedRequests = ref<FriendRequestInfo[]>([]);
const sentRequests = ref<FriendRequestInfo[]>([]);

// 获取收到的好友请求
const loadReceivedRequests = async () => {
  try {
    const res = await getFriendRequests({ type: "received", status: "pending" });
    receivedRequests.value = res.data || [];
  } catch (error) {
    console.error("获取收到的好友请求失败:", error);
    ElMessage.error("获取好友请求失败，请稍后重试");
  }
};

// 获取发出的好友请求
const loadSentRequests = async () => {
  try {
    const res = await getFriendRequests({ type: "sent" });
    sentRequests.value = res.data || [];
  } catch (error) {
    console.error("获取发出的好友请求失败:", error);
    ElMessage.error("获取好友请求失败，请稍后重试");
  }
};

// 接受好友请求
const acceptRequest = async (request: FriendRequestInfo) => {
  try {
    await ElMessageBox.confirm(`是否接受来自 ${request.senderName} 的好友请求？`, "确认操作", {
      confirmButtonText: "接受",
      cancelButtonText: "取消",
      type: "info",
    });

    await acceptFriendRequest(request.id);
    ElMessage.success("已接受好友请求");
    // 重新加载请求列表
    loadReceivedRequests();
  } catch (error) {
    if (error !== "cancel") {
      console.error("接受好友请求失败:", error);
      ElMessage.error("接受好友请求失败，请稍后重试");
    }
  }
};

// 拒绝好友请求
const rejectRequest = async (request: FriendRequestInfo) => {
  try {
    await ElMessageBox.confirm(`是否拒绝来自 ${request.senderName} 的好友请求？`, "确认操作", {
      confirmButtonText: "拒绝",
      cancelButtonText: "取消",
      type: "warning",
    });

    await rejectFriendRequest(request.id);
    ElMessage.success("已拒绝好友请求");
    // 重新加载请求列表
    loadReceivedRequests();
  } catch (error) {
    if (error !== "cancel") {
      console.error("拒绝好友请求失败:", error);
      ElMessage.error("拒绝好友请求失败，请稍后重试");
    }
  }
};

// 取消好友请求
const cancelRequest = async (request: FriendRequestInfo) => {
  try {
    await ElMessageBox.confirm(`是否取消发送给 ${request.receiverName} 的好友请求？`, "确认操作", {
      confirmButtonText: "取消请求",
      cancelButtonText: "返回",
      type: "warning",
    });

    // 假设此处有取消请求的API
    // await cancelFriendRequest(request.id);
    ElMessage.success("已取消好友请求");
    // 重新加载请求列表
    loadSentRequests();
  } catch (error) {
    if (error !== "cancel") {
      console.error("取消好友请求失败:", error);
      ElMessage.error("取消好友请求失败，请稍后重试");
    }
  }
};

// 返回好友列表
const goBack = () => {
  router.push("/social/friends");
};

// 截断消息内容
const truncateMessage = (message: string) => {
  if (!message) return "";
  return message.length > 20 ? message.substring(0, 20) + "..." : message;
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return "";
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  // 小于1天
  if (diff < 86400000) {
    return date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
  }
  // 小于7天
  else if (diff < 604800000) {
    const days = ["日", "一", "二", "三", "四", "五", "六"];
    return `周${days[date.getDay()]} ${date.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" })}`;
  }
  // 大于7天
  else {
    return date.toLocaleDateString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  }
};

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case "pending":
      return "info";
    case "accepted":
      return "success";
    case "rejected":
      return "danger";
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "pending":
      return "等待处理";
    case "accepted":
      return "已接受";
    case "rejected":
      return "已拒绝";
    default:
      return "未知状态";
  }
};

onMounted(() => {
  // 自动重定向到新的社交中心页面，并设置标记打开好友请求对话框
  localStorage.setItem("openFriendRequests", "true");
  router.replace("/social/index");
});
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.request-list {
  margin-top: 20px;
}

.request-card {
  margin-bottom: 15px;

  .request-info {
    display: flex;
    align-items: flex-start;
    margin-bottom: 15px;

    .el-avatar {
      margin-right: 15px;
    }

    .request-details {
      flex: 1;

      .request-name {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 4px;
      }

      .request-time {
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;
      }

      .request-message,
      .request-status {
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .request-actions {
    display: flex;
    justify-content: flex-end;

    .el-button {
      margin-left: 10px;
    }
  }
}
</style>
